﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using Medianamik.Client.MVP.Model.Service;
using Medianamik.Client.MVP.Presentation;
using StructureMap;
using StructureMap.Pipeline;

namespace Medianamik.Client.MVP.View
{
    public abstract class UserControlViewWithPresenter<T> : UserControl, IView
        where T : class
    {
        protected T Presenter;
        public event EventHandler Initialize;

        protected override void OnInit(EventArgs e)
        {
            Presenter = NewPresenter();
            base.OnInit(e);
        }
        protected override void OnLoad(EventArgs e)
        {
            // Attention, le Initialize doit se faire AVANT l'événement OnLoad car des propriété qui sont 
            // settés dans le Initialize sont utilisées dans OnLoad
            OnInitialize(e);
            base.OnLoad(e);
        }

        private void OnInitialize(EventArgs e)
        {
            if (Initialize != null)
                Initialize(this, e);
        }

        public virtual Guid NodeId
        {
            get { return ObjectFactory.GetInstance<ICurrentNodeIdRetriever>().CurrentNodeId; }
        }

        public bool IsValid
        {
            get { return Page.IsValid; }
        }

        protected virtual T NewPresenter()
        {
            return ObjectFactory
                .GetInstance<T>(new ExplicitArguments(new
                Dictionary<string, object> { { "view", this } }));
        }

        /// <summary>
        /// Redirige le browser vers le URL indiqué
        /// </summary>
        /// <param name="url"></param>
        public void Redirect(string url)
        {
            Response.Redirect(url);
        }
    }
}